import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios'
interface HomeState {
	count: number
	list: string[],
	loading: boolean
	error: string | null

}

const initialState: HomeState = {
	count: 1,
	list: [],
	loading: true,
	error: null
}
// 异步action
export const fetchListData = createAsyncThunk(
	'home/fetchListData',
	async () => {
		const resp = await axios.get('/api/list')
		return resp.data
	}
)

const homeReducer = createSlice({
	name: 'home',
	initialState,
	// 同步action
	reducers: {
		addCount(state) {
			state.count++
		},
		addCustomCount(state, action: PayloadAction<number>) {
			state.count += action.payload
		}
	},
	extraReducers: {
		[fetchListData.pending.type](state) {
			state.loading = true
		},
		[fetchListData.fulfilled.type](state, action) {
			state.list = action.payload
			state.loading = false
		},
		[fetchListData.rejected.type](state, action) {
			state.loading = false
			state.error = '请求数据失败'
		}
	}
})

export const { addCount, addCustomCount } = homeReducer.actions
export default homeReducer.reducer
